import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();
const request = axios.create({
  timeout: 60000,
  withCredentials: false,
  headers: {
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
  },
});
const token = sessionStorage.getItem("token") || "";

request.interceptors.request.use(
  (config) => {
    if (token) {
      config.headers.authorization = "Bearer " + token;
    }

    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    switch (response.data.status) {
      case "401":
        ElMessage({
          type: "error",
          message: "登录过期，请重新登录",
        });
        sessionStorage.removeItem("token");
        setTimeout(() => {
          router.replace({
            path: "/login",
          });
        }, 1000);
        break;

      default:
        return response;
    }
    return response;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

export default request;
